package com.qizhidao.j2cache.redis;


import net.oschina.j2cache.CacheChannel;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;

public class J2CacheTemplate extends RedisTemplate<String, String> {

    private J2CacheValueOperations<String, String> valueOps;

    public J2CacheTemplate(CacheChannel channel, String region) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        this.setKeySerializer(stringSerializer);
        this.setValueSerializer(stringSerializer);
        this.setHashKeySerializer(stringSerializer);
        this.setHashValueSerializer(stringSerializer);
        valueOps = new J2CacheValueOperations<>(this, channel, region);
    }

    public J2CacheTemplate(RedisConnectionFactory connectionFactory, CacheChannel channel, String region) {
        this(channel, region);
        this.setConnectionFactory(connectionFactory);
        this.afterPropertiesSet();
    }

    @Override
    public Boolean delete(String key) {
        return valueOps.delete(key);
    }

    @Override
    public Long delete(Collection<String> keys) {
        valueOps.delete(keys.toArray(new String[keys.size()]));
        return Long.valueOf(keys.size());
    }


    @Override
    public J2CacheValueOperations<String, String> opsForValue() {
        return valueOps;
    }

    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
        return connection;
//        return new DefaultStringRedisConnection(connection);
    }
}
